package com.eqdd.yiqidian.ui.gongneng.kehu;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.eqdd.nextinputs.Scheme;
import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.yiqidian.AddKehuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.ui.base.EditTextActivity;
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity;
import com.eqdd.yiqidian.utils.PermissionTipUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ActionSheetDialog;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;

public class AddLianxirenActivity extends SlimBaseMultiEditActivity {
    private static final int PICK_CONTACT = 10;
    private AddKehuActivityCustom dataBinding;
    private String name;
    private String departmentName;
    private String careerName;
    private String phone;
    private String qq;
    private String weixin;
    private String email;
    private String msg;
    private int type;
    //    @ToSave
    String cusid;
    private ArrayList<Scheme> schemes;
    private ActionSheetDialog bottomChoose;


    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_kehu);
        initTopTitleBar(View.VISIBLE, "添加联系人");
        initTopRightText("添加", v -> {
            if (checkParam()) {
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.KEHU_ADD_LIANXIREN)
                        .params("name", setParam(0))
                        .params("owner", user.getGuid())
                        .params("dep", setParam(1))
                        .params("post", setParam(2))
                        .params("cellphone", setParam(3))
                        .params("conqq", setParam(4))
                        .params("conwx", setParam(5))
                        .params("email", setParam(6))
                        .params("remark", setParam(7))
                        .params("cusid", cusid)
                        .execute(new DialogCallBack<HttpResult>(AddLianxirenActivity.this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult httpResult = response.body();
                                ToastUtil.showShort(httpResult.getMsg());
                                if (httpResult.getStatus() == 200) {
                                    clearData();
                                    setResult(Config.SUCCESS);
                                    finish();
                                }
                            }
                        });
            } else {
                ToastUtil.showShort(msg);
            }
        });
        type = getIntent().getIntExtra(Config.TYPE, -1);
        if (type != -1) {
            isRead = false;
        }
        name = getIntent().getStringExtra(Config.USER_NAME);
        cusid = getIntent().getStringExtra("cusid");
        departmentName = getIntent().getStringExtra(Config.DEPARTMENT_NAME);
        careerName = getIntent().getStringExtra(Config.CAREER_NAME);
        phone = getIntent().getStringExtra(Config.PHONE);
        qq = getIntent().getStringExtra(Config.QQ);
        weixin = getIntent().getStringExtra(Config.WEIXIN);
        email = getIntent().getStringExtra(Config.EMAIL);
    }


    private boolean checkParam() {
        if (TextUtils.isEmpty(datas.get(0).getContent())) {
            msg = "请输入姓名";
            return false;
        }
        if (TextUtils.isEmpty(datas.get(2).getContent())) {
            msg = "请输入职务";
            return false;
        }
        if (TextUtils.isEmpty(datas.get(3).getContent())) {
            msg = "请输入手机";
            return false;
        }
        return true;
    }


    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {

        switch (slimAdapterEx.getDataItem(p).getPosition()) {
            case 0:
            case 3:
                ChooseAlertView.getBottomChoose(this, "请选择", new String[]{"通讯录选择", "手动输入"},
                        (o, position) -> {
                            if (position == 1) {
                                RxPermissions.getInstance(AddLianxirenActivity.this)
                                        .request(android.Manifest.permission.READ_CONTACTS)
                                        .subscribe(isGrant -> {
                                            if (isGrant) {
                                                Intent intent = new Intent(Intent.ACTION_PICK);
                                                intent.setType(ContactsContract.Contacts.CONTENT_TYPE);//vnd.android.cursor.dir/contact
                                                startActivityForResult(intent, PICK_CONTACT);
                                            } else {
                                                PermissionTipUtil.tip(AddLianxirenActivity.this, "通讯录");
                                            }
                                        });

                            } else if (position == 2) {
                                SlimEditEnterBean slimEditEnterBean = (SlimEditEnterBean) slimAdapterEx.getDataItem(p);
                                Bundle bundle = new Bundle();
                                bundle.putString("content", slimEditEnterBean.getContent());
                                bundle.putString("tip", TextUtils.isEmpty(slimEditEnterBean.getTip()) ? slimEditEnterBean.getTitle() : slimEditEnterBean.getTip());
                                bundle.putString("title", slimEditEnterBean.getTitle());
                                bundle.putBoolean("canBlank", slimEditEnterBean.isCanBlank());
                                AppConstent.schemes = slimEditEnterBean.getSchemes();
                                startActivityForResult(EditTextActivity.class, bundle, p);
                            }
                        }).show();
                break;
        }
    }

    @Override
    protected void setEditBeans() {

        datas.add(new SlimEditEnterBean("*姓名", name, 0, true, "请输入(必填)"));
        datas.add(new SlimEditEnterBean("部门", departmentName, 1, "请输入"));
        datas.add(new SlimEditEnterBean("*职务", careerName, 2, "请输入(必填)"));
        schemes = new ArrayList<>();
        schemes.add(StaticScheme.ChineseMobile());
        datas.add(new SlimEditEnterBean("*手机", phone, 3, true, "请输入(必填)").setSchemes(schemes));
        datas.add(new SlimEditEnterBean("QQ", qq, 4, "请输入"));
        datas.add(new SlimEditEnterBean("微信", weixin, 5, "请输入"));

        schemes = new ArrayList<>();
        schemes.add(StaticScheme.Email());
        datas.add(new SlimEditEnterBean("邮箱", email, 6, "请输入").setSchemes(schemes).setCanBlank(true));
        datas.add(new SlimEditEnterBean("备注", "", 7, "请填写"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PICK_CONTACT) {
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = managedQuery(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).replace(" ", "");
                    String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    String phoneNumber = null;
                    if (hasPhone.equalsIgnoreCase("1")) {
                        hasPhone = "true";
                    } else {
                        hasPhone = "false";
                    }
                    if (Boolean.parseBoolean(hasPhone)) {
                        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                                        + contactId,
                                null,
                                null);
                        while (phones.moveToNext()) {
                            phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            phoneNumber = phoneNumber.replace(" ", "").replace("-", "");
                        }
                        phones.close();
                    }
                    slimAdapterEx.getDataItem(0).setContent(name);
                    slimAdapterEx.getDataItem(3).setContent(phoneNumber);
                    slimAdapterEx.notifyItemChanged(0);
                    slimAdapterEx.notifyItemChanged(3);
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
